package com.pf.common.exception;

import com.pf.common.dto.ResultResp;
import com.pf.common.enums.ResultRespEnum;
import com.pf.common.utils.ResultRespUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author PanFei
 * @version 1.0.0
 * @createTime 2022/6/25 17:55
 */
@RestControllerAdvice(basePackages = {"com.pf"})
public class GlobalExceptionHandler {
    /**
     * 异常统一处理
     * 非法参数异常 {@link IllegalArgumentException}
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public ResultResp<?> exceptionHandler(Exception e) {
        e.printStackTrace();
        ResultResp<?> baseResult;
        if (e instanceof IllegalArgumentException) {
            baseResult = ResultRespUtils.fail(ResultRespEnum.PARAM_ERROR.getCode(), e.getMessage());
        } else if (e instanceof BusinessException) {
            BusinessException businessException = (BusinessException) e;
            baseResult = ResultRespUtils.fail(businessException.getCode(), businessException.getMessage());
        } else {
            baseResult = ResultRespUtils.fail(ResultRespEnum.SYSTEM_ERROR);
        }
        return baseResult;
    }

    /**
     * 接口入参的validate校验
     *
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultResp<?> methodArgumentNotValidExceptionHandle(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        String errorMsg = null;
        for (FieldError error : bindingResult.getFieldErrors()) {
            errorMsg = "错误字段：" + error.getField() + "===>错误信息：" + error.getDefaultMessage();
            break;
        }
        return ResultRespUtils.fail(ResultRespEnum.PARAM_ERROR.getCode(), errorMsg);
    }
}
